import utils
from random import random
from math import cos, radians


class Cherry:

    def __init__(self, pen):
        self.pen = pen
        self.pen.hideturtle()
        self.pen.speed(100)
        self.pen.left(90)
        utils.Utils.penMove(self.pen, -utils.width // 4 - 50, -utils.height // 3 - 50)

    def __enter__(self):
        return self

    def __exit__(self, exp_type, exp_value, exp_traceback):
        del self

    def tree(self, n, l):
        self.pen.pd()  # 下笔
        # 阴影效果
        t = cos(radians(self.pen.heading() + 45)) / 8 + 0.25
        self.pen.pencolor(t, t, t)
        self.pen.pensize(n / 3)
        self.pen.forward(l)  # 画树枝
        if n > 0:
            b = random() * 15 + 10  # 右分支偏转角度
            c = random() * 15 + 10  # 左分支偏转角度
            d = l * (random() * 0.25 + 0.7)  # 下一个分支的长度
            # 右转一定角度,画右分支
            self.pen.right(b)
            self.tree(n - 1, d)
            # 左转一定角度，画左分支
            self.pen.left(b + c)
            self.tree(n - 1, d)
            # 转回来
            self.pen.right(c)
        else:
            # 画叶子
            self.pen.right(90)
            n = cos(radians(self.pen.heading() - 45)) / 4 + 0.5
            self.pen.pencolor(n, n * 0.8, n * 0.8)
            self.pen.circle(3)
            self.pen.left(90)
            # 添加0.3倍的飘落叶子
            if random() > 0.7:
                self.pen.pu()
                # 飘落
                t = self.pen.heading()
                an = -40 + random() * 40
                self.pen.setheading(an)
                dis = int(
                    800 * random() * 0.5 + 400 * random() * 0.3 + 200 * random() * 0.2
                )
                self.pen.forward(dis)
                self.pen.setheading(t)
                # 画叶子
                self.pen.pd()
                self.pen.right(90)
                n = cos(radians(self.pen.heading() - 45)) / 4 + 0.5
                self.pen.pencolor(n * 0.5 + 0.5, 0.4 + n * 0.4, 0.4 + n * 0.4)
                self.pen.circle(2)
                self.pen.left(90)
                self.pen.pu()
                # 返回
                t = self.pen.heading()
                self.pen.setheading(an)
                self.pen.backward(dis)
                self.pen.setheading(t)
        self.pen.pu()
        self.pen.backward(l)  # 退回
